<template>
  <div class="task-list-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2>任务列表</h2>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="showTaskForm = true">
          <el-icon><Plus /></el-icon>
          新建任务
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics" v-if="statistics">
      <div class="stat-item">
        <span class="stat-label">待办</span>
        <span class="stat-value">{{ statistics.todoCount || 0 }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">进行中</span>
        <span class="stat-value">{{ statistics.inProgressCount || 0 }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">已完成</span>
        <span class="stat-value">{{ statistics.completedCount || 0 }}</span>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <TaskFilter
      v-model:keyword="filters.keyword"
      v-model:status="filters.status"
      v-model:priority="filters.priority"
      v-model:sort-by="filters.sortBy"
      v-model:sort-order="filters.sortOrder"
      @search="loadTasks"
    />

    <!-- 任务列表 -->
    <div class="tasks" v-loading="loading">
      <div v-if="tasks.length === 0" class="empty">
        <el-empty description="暂无任务" />
      </div>
      <div
        v-for="task in tasks"
        :key="task.taskId"
        class="task-card"
        :class="{ completed: task.status === 'COMPLETED' }"
      >
        <div class="task-header">
          <div class="task-title-row">
            <span
              class="priority-dot"
              :class="`priority-${task.priority.toLowerCase()}`"
            ></span>
            <h3 class="task-title">{{ task.title }}</h3>
          </div>
          <div class="task-actions">
            <el-dropdown @command="(cmd) => handleStatusChange(task, cmd)">
              <el-button size="small">
                {{ getStatusText(task.status) }}
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="TODO">待办</el-dropdown-item>
                  <el-dropdown-item command="IN_PROGRESS">进行中</el-dropdown-item>
                  <el-dropdown-item command="COMPLETED">已完成</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button size="small" @click="handleEdit(task)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(task)">删除</el-button>
          </div>
        </div>

        <p class="task-description" v-if="task.description">
          {{ task.description }}
        </p>

        <div class="task-footer">
          <div class="task-meta">
            <el-tag v-if="task.categoryName" size="small" :color="task.categoryColor">
              {{ task.categoryName }}
            </el-tag>
            <span class="task-date" v-if="task.dueDate">
              📅 {{ formatDate(task.dueDate) }}
              <el-tag
                v-if="getDueDateStatus(task.dueDate, task.status)"
                :type="getDueDateType(task.dueDate)"
                size="small"
              >
                {{ getDueDateStatus(task.dueDate, task.status) }}
              </el-tag>
            </span>
          </div>
          <div class="task-timer">
            <span class="timer-info" v-if="task.totalTime">
              ⏱️ {{ formatDuration(task.totalTime) }}
            </span>
            <el-button
              size="small"
              type="primary"
              @click="handleStartTimer(task)"
            >
              <el-icon><Timer /></el-icon>
              开始计时
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 任务表单对话框 -->
    <TaskForm
      v-model="showTaskForm"
      :task="currentTask"
      :categories="categories"
      @success="handleTaskSuccess"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTaskList, deleteTask, updateTaskStatus } from '../api/task'
import { startTimer } from '../api/timer'
import TaskFilter from './TaskFilter.vue'
import TaskForm from './TaskForm.vue'

const props = defineProps({
  selectedCategoryId: {
    type: Number,
    default: null
  },
  categories: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['refresh-categories', 'timer-start'])

const loading = ref(false)
const tasks = ref([])
const statistics = ref(null)
const showTaskForm = ref(false)
const currentTask = ref(null)

const filters = ref({
  keyword: '',
  status: '',
  priority: '',
  sortBy: 'createdAt',
  sortOrder: 'DESC'
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    const params = {
      ...filters.value,
      categoryId: props.selectedCategoryId
    }
    
    console.log('请求参数:', params)
    const response = await getTaskList(params)
    console.log('响应数据:', response)
    
    tasks.value = response.data.tasks || []
    statistics.value = response.data.statistics || {}
  } catch (error) {
    console.error('加载任务失败:', error)
    ElMessage.error('加载任务失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 状态变更
const handleStatusChange = async (task, newStatus) => {
  try {
    await updateTaskStatus(task.taskId, newStatus)
    ElMessage.success('状态更新成功')
    loadTasks()
    emit('refresh-categories')
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

// 编辑任务
const handleEdit = (task) => {
  currentTask.value = { ...task }
  showTaskForm.value = true
}

// 删除任务
const handleDelete = async (task) => {
  try {
    await ElMessageBox.confirm(`确定要删除任务"${task.title}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteTask(task.taskId)
    ElMessage.success('删除成功')
    loadTasks()
    emit('refresh-categories')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
    }
  }
}

// 任务操作成功
const handleTaskSuccess = () => {
  showTaskForm.value = false
  currentTask.value = null
  loadTasks()
  emit('refresh-categories')
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    TODO: '待办',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 获取截止日期状态
const getDueDateStatus = (dueDate, status) => {
  if (!dueDate || status === 'COMPLETED') return ''
  
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const due = new Date(dueDate)
  due.setHours(0, 0, 0, 0)
  
  const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) return '已过期'
  if (diffDays === 0) return '今天到期'
  if (diffDays === 1) return '明天到期'
  return ''
}

// 获取截止日期类型
const getDueDateType = (dueDate) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const due = new Date(dueDate)
  due.setHours(0, 0, 0, 0)
  
  const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) return 'danger'
  if (diffDays <= 1) return 'warning'
  return 'info'
}

// 格式化持续时长
const formatDuration = (seconds) => {
  if (!seconds) return '0分钟'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟`
  } else {
    return `${seconds}秒`
  }
}

// 开始计时
const handleStartTimer = async (task) => {
  try {
    await startTimer(task.taskId)
    ElMessage.success('计时已开始')
    emit('timer-start')
  } catch (error) {
    console.error('开始计时失败:', error)
    if (error.message && error.message.includes('已有正在运行的计时器')) {
      ElMessage.warning('已有正在运行的计时器，请先停止当前计时')
    } else {
      ElMessage.error('开始计时失败')
    }
  }
}

// 监听分类变化
watch(() => props.selectedCategoryId, () => {
  loadTasks()
})

onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-list-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toolbar h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.statistics {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
}

.tasks {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.task-card {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.task-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.task-card.completed {
  opacity: 0.7;
}

.task-card.completed .task-title {
  text-decoration: line-through;
  color: #909399;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.task-title-row {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.priority-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.priority-high {
  background-color: #f56c6c;
}

.priority-medium {
  background-color: #e6a23c;
}

.priority-low {
  background-color: #67c23a;
}

.task-title {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.task-actions {
  display: flex;
  gap: 8px;
}

.task-description {
  margin: 10px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.task-date {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 5px;
}

.task-timer {
  display: flex;
  align-items: center;
  gap: 10px;
}

.timer-info {
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
}

.empty {
  padding: 40px 0;
  text-align: center;
}
</style>
